package com.yonyou.ucf.mdf.app.isvdxq.secondpart.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.ProductEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.WarehouseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.ProductService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.WarehouseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.PrelableEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpclistService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpcotherService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.PrelableService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.StorerecordService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/epclist",DxqConfig.pre_pcUrl+"/epclist"})
public class EpclistController {
    @Autowired
    BaseService baseService;
    @Autowired
    EpclistService epclistService;
    @Autowired
    PrelableService prelableService;
    @Autowired
    OrderNoticeService orderNoticeService;
    @Autowired
    WarehouseService warehouseService;
    @Autowired
    ProductService productService;

    @RequestMapping("/ViewPage")
    public DataResult ViewPage(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        try {
            Map params = RequestTool.getParamsPage(request, result);
            int pagenum = result.getPageNum();
            int pagesize = result.getPageSize();
            int m = result.initStartNumber();
            List<EpcEntity> dataList = epclistService.SelectPage(tenantId, m, pagesize);
            result = new DataResult(1, "操作成功");
            result.setDataList(dataList);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 所有数据列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/ViewList")
    public DataResult ViewList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        List<EpcEntity> epcEntities = epclistService.SelectAll(tenantId);
        result = new DataResult(1, "操作成功");
        result.setDataList(epcEntities);

        return result;
    }

    /***
     * 历史库存发签: epc,count,productdate,invalidDate,batchno,warehouseId,proId,proskuId,unitId/stockUnitId
     * @param request
     * @return
     */
    @RequestMapping("/EntityIn")
    public DataResult EntityIn(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> myParams = RequestTool.getParams(request);
            List<EpcEntity> datalist = new ArrayList<>();
            String datalistObj = myParams.get("datalist");
            if (StringUtils.isNotEmpty(datalistObj)) {
                datalistObj = datalistObj.contains("%") ? URLDecoder.decode(datalistObj, "utf-8") : datalistObj;
                datalist = JSONObject.parseArray(datalistObj, EpcEntity.class);
            }
            if (StringUtils.isEmpty(tenantId) || StringUtils.isEmpty(userId)) {
                result.setMessage("参数异常");
                return result;
            }
            String batch_no = MyTool.GenerateCode();
            if (datalist.size() == 0) return result;
            for (EpcEntity item : datalist) {
                item.setYtenant_id(tenantId);
                item.setRfid_status(7);
                item.setBatch_no(batch_no);
                item.setF_move_count(Double.valueOf(0));
                item.setF_out_count(Double.valueOf(0));
                item.setCreator(userId);
                item.setModifier(userId);
                item.setCreate_time(MyTool.GenerateTime());
                item.setModify_time(MyTool.GenerateTime());
                item.setId(MyTool.getRandomId());
                item.setPubts(MyTool.GenerateTime());
                item.setStockUnitId(item.getUnitId());
                item.setStock_unit_name(item.getUnit_name());
                String remarkString = StringUtils.isEmpty(item.getRemark()) ? "" : item.getRemark();
                item.setRemark(String.format("%s|%s", "库存补签", remarkString));
            }
            Integer rInt = epclistService.InsertBatch(datalist);

            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /***
     * 标签状态修改
     * 打印机服务器请求、或手持请求
     * 7 to 0
     * @param request
     * @return
     */
    @RequestMapping("/EntityStatusEdit")
    public DataResult EntityStatusEdit(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> myParams = RequestTool.getParams(request);
            String epcs = (String) myParams.get("epcs");
            Integer status = (Integer) myParams.get("status");
            List<String> epcList = new ArrayList<>();
            if (StringUtils.isNotEmpty(epcs)) {
                epcList = Arrays.asList(epcs.split(","));
            }
            List<EpcEntity> epcEntities = epclistService.SelectByEpcs(epcList, tenantId);
            List<String> ids = epcEntities.stream().map(it -> it.getId()).collect(Collectors.toList());
            if (ids.size() == 0 || status == null) return result;
            Integer rInt = epclistService.EditStatus(ids, status, userId, tenantId);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 拆合签 - 合签：业务场景用于仓库理货
     * 合并EPC 保留首个
     * 合签备份原签，合签
     *
     * @param epcs    第一个为保留EPC,支持多个标签合并
     * @param request
     * @return
     */
    @RequestMapping("/MergeEpc")
    public DataResult MergeEpc(@RequestBody List<String> epcs, HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> myParmas = RequestTool.getParams(request);
            String epcString = myParmas.get("epcs");
            if (StringUtils.isNotEmpty(epcString)) {
                epcs = Arrays.asList(epcString.split(","));
            }
            if (epcs == null || epcs.size() == 0) return result;
            List<EpcEntity> listEntity = epclistService.SelectByEpcs(epcs, tenantId);
            if (listEntity == null || epcs == null || listEntity.size() == 0 || listEntity.size() != epcs.size()) {
                result.setMessage("参数异常");
                return result;
            }
            int checkNum = listEntity.stream().map(it -> it.getProduct_id() + "|" + it.getProduct_sku_id()).distinct()
                    .collect(Collectors.toList()).size();
            if (checkNum != 1) {
                result.setMessage("物料不一致");
                return result;
            }
            int checkNum2 = listEntity.stream().map(it -> it.getBatchno()).distinct()
                    .collect(Collectors.toList()).size();
            if (checkNum2 != 1) {
                result.setMessage("物料批次不一致");
                return result;
            }
            //状态验证
            int checkNum3 = listEntity.stream().filter(it -> it.getRfid_status() != 1).distinct().collect(Collectors.toList()).size();
            if (checkNum3 > 0) {
                result.setMessage("非正常库存，不允许合签");
                return result;
            }

            //跨库验证
            int checkNum4 = listEntity.stream().map(it -> it.getWarehouse_id()).distinct().collect(Collectors.toList()).size();
            if (checkNum4 != 1) {
                result.setMessage("跨库，不允许合签");
                return result;
            }
            String epccode = epcs.get(0);//保留首个
            double moveCount = listEntity.stream().filter(it -> !it.getRfid_code().equals(epccode))
                    .mapToDouble(it -> it.getF_move_count()).sum();
            double outCount = listEntity.stream().filter(it -> !it.getRfid_code().equals(epccode))
                    .mapToDouble(it -> it.getF_out_count()).sum();
            if (moveCount > 0 || outCount > 0) {
                result.setMessage("移库出库占用");
                return result;
            }
            //获取最小保质期
            EpcEntity minEpcEntity = listEntity.stream().filter(it -> !StringUtils.isEmpty(it.getInvalidDate()))
                    .min(Comparator.comparing(EpcEntity::getInvalidDate)).orElse(null);
            String timeEnd = minEpcEntity == null ? null : minEpcEntity.getInvalidDate();
            double totalCount = listEntity.stream().mapToDouble(it -> it.getF_stock_count()).sum();
            EpcEntity entity = listEntity.stream().filter(it -> it.getRfid_code().equals(epccode)).findFirst().get();
            if (entity == null) return result;
            entity.setInvalidDate(timeEnd);
            entity.setF_stock_count(totalCount);

            int rInt = epclistService.MergeEpc(entity, epcs, tenantId);
            result = new DataResult(1, "操作成功");
            result.setData(entity);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 拆合签 - 拆签
     * 1、继承上架状态、货位信息、仓库、托盘信息、物料信息；
     * 2、修改epc信息、库存量
     * 3、拣货、出库、盘点等业务影响排除；
     * 合签
     * 1、验证同库作业，同物料信息；
     * 2、修改保留目标epc信息、更新库存量
     * 3、拣货、出库、盘点等业务影响排除；
     * todo 解除record表强关联，实现多对多关系
     * 拆签数据  或者拆签时补入库记录； 已处理
     * todo 使用时需要Source_code补查记录；
     *
     * @param epc     原签EPC
     * @param epcnew  新签EPC
     * @param count   新签EPC代表数量
     * @param request
     * @return
     */
    @RequestMapping("/SplitEpc")
    public DataResult SplitEpc(String epc, String epcnew, String count, HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> myParmas = RequestTool.getParams(request);
            if (StringUtils.isEmpty(epc) || StringUtils.isEmpty(epcnew)) {
                result.setMessage("参数不能为空");
                return result;
            }
            if (StringUtils.isEmpty(count) || Integer.valueOf(count) <= 0) {
                result.setMessage("参数异常");
                return result;
            }
            EpcEntity tempEntity = epclistService.SelectByEpc(epcnew, tenantId);
            if (tempEntity != null) {
                result.setMessage("标签物料占用");
                return result;
            }
            int[] arrStatus = new int[]{0, 1};
            EpcEntity entity = epclistService.SelectByEpc(epc, tenantId);
            if (MyTool.findIndex(arrStatus, entity.getRfid_status()) == -1) {
                result.setMessage("物料状态异常");
                return result;
            }
            double countMove = entity.getF_move_count() == null ? 0 : entity.getF_move_count();
            double countOut = entity.getF_out_count() == null ? 0 : entity.getF_out_count();
            double CountCur = entity.getF_stock_count() - countMove - countOut;
            if (StringUtils.isEmpty(count)) {
                return result;
            } else if (!StringUtils.isEmpty(count) && CountCur < Double.parseDouble(count)) {
                result.setMessage("库存不够");
                return result;
            }

            EpcEntity entityNew = MyTool.convertBean2Bean(entity, EpcEntity.class);
            entityNew.setSource_code(entity.getRfid_code());
            entityNew.setF_stock_count(Double.valueOf(count));
            entityNew.setRfid_code(epcnew);
            entityNew.setId(MyTool.getRandomId());
            entityNew.setIs_split(1);//拆签
            entity.setF_stock_count(CountCur - entityNew.getF_stock_count());

            int rInt = epclistService.SplitEpc(entity, entityNew, tenantId);
            result = new DataResult(1, "操作成功");
            result.setData(entityNew);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }

        return result;
    }

    @RequestMapping("/GetListPrelable")
    public DataResult GetListPrelable(String orderid, String orderdetailid, HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        List<PrelableEntity> datalist = prelableService.SelectByOrder(orderid, orderdetailid, 0, tenantId);
        result = new DataResult(1, "操作成功");
        result.setDataList(datalist);
        return result;
    }

    /**
     * 预发标签
     *
     * @param orderid
     * @param orderdetailid
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/AddPrelable")
    public DataResult AddPrelable(String orderid, String orderdetailid, HttpServletRequest request) throws IOException {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        Map<String, Object> reqParams = RequestTool.getParams(request);
        double stocknum = (double) reqParams.get("stocknum");
        String batchno = (String) reqParams.get("batchno");//接收到货批次号
        String productdate = (String) reqParams.get("productdate");
        String modifier = (String) reqParams.get("modifier");
        //生产EPC
        String epccode = MyTool.GenerateEpc("A01");

        PrelableEntity entity = new PrelableEntity();
        entity.setOrderid(orderid);
        entity.setOrderdetailid(orderdetailid);
        entity.setEpc_tid("");
        entity.setEpccode(epccode);
        entity.setYtenant_id(tenantId);
        entity.setStockNum(stocknum);
        entity.setBatchno(batchno);
        entity.setProductdate(productdate);
        entity.setCreator(modifier);
        entity.setCreateTime(MyTool.GenerateTime());
        //物料、仓库
        DataResult tempResDH = epclistService.GetOrderDH(orderid, orderdetailid, tenantId);
        if (tempResDH.getStatus() != 1) return tempResDH;
        OrderDetailDHBean tempBean = (OrderDetailDHBean) tempResDH.getData();
        String ordercode = tempBean.getCode();
        entity.setOrdercode(ordercode);
        List<OrderDetailDHBean.DetailDHItem> itemEntityList = tempBean.getArrivalOrders().stream()
                .filter(it -> it.getId().equals(orderdetailid)).collect(Collectors.toList());
        if (itemEntityList == null || itemEntityList.size() == 0) return result;
        OrderDetailDHBean.DetailDHItem itemEntity = itemEntityList.get(0);
        if (itemEntity == null) return result;

        String warehouseId = itemEntity.getWarehouse();
        String warehouseName = itemEntity.getWarehouse_name();
        entity.setWarehouseId(warehouseId);
        entity.setWarehousecode("");
        entity.setWarehousename(warehouseName);
        entity.setProductclassId(itemEntity.getProductClass());
        entity.setProductclasscode(itemEntity.getProductClass_Code());
        entity.setProductclassname(itemEntity.getProductClass_Name());
        entity.setProductId(itemEntity.getProduct());
        entity.setProductcode(itemEntity.getProduct_cCode());
        entity.setProductname(itemEntity.getProduct_cName());
        entity.setProductskuId(itemEntity.getProductsku());
        entity.setProductskucode(itemEntity.getProductsku_cCode());
        entity.setProductskuname(itemEntity.getProductsku_cName());
        entity.setUnitId(itemEntity.getUnit());
        entity.setUnitcode("");
        entity.setUnitname(itemEntity.getUnit_name());

        String productCode = itemEntity.getProduct_cCode();

        int rInt = prelableService.InsertEntity(entity);
        if (rInt > 0) {
            result = new DataResult(1, "操作成功");
        }
        return result;
    }

    @Autowired
    StorerecordService storerecordService;

    /**
     * orderid == null||undefined 无单据来源
     * PC 发签入库 仅支持有到货单的发签入库，涉及回写到货单据更新
     * todo 历史库存补签方案
     * 单仓库 单物料作业
     *
     * @param paramData
     * @param request
     * @return
     * @throws Exception
     */
    //本地提交(写入物料库存)，提交打印机(客户端)，提交用友(组装数据提交用友)，本地回写(storerecord)
    @RequestMapping("/SubmitEpclist")
    public DataResult SubmitEpclist(@RequestBody Map<String, Object> paramData, HttpServletRequest request) throws Exception {
        DataResult result = new DataResult(0, "操作失败");
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        List<PrelableEntity> epcprelist = (List<PrelableEntity>) paramData.get("epcprelist");
        List<String> ids = (List<String>) paramData.get("ids");
        //接收参数
        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        String ordertype = (String) reqParams.get("ordertype");
        String flagdebug = (String) reqParams.get("flagdebug");
        //List<PrelableEntity> epcprelist = prelableService.SelectByIds(ids, tenantId);
        epcprelist = JSONObject.parseArray(JSONObject.toJSONString(epcprelist), PrelableEntity.class);
        // 服务端生成epc编码
        String flagepc = (String) reqParams.get("flagepc");
        if (flagepc != null && flagepc.equals("true")) {
            for (PrelableEntity item : epcprelist) {
                //生产EPC
                String epccode = MyTool.GenerateEpc("A01");
                item.setEpccode(epccode);
            }
        }

        PrelableEntity tempEntity = epcprelist.get(0);
        if (tempEntity == null) return result;
        String orderid = tempEntity.getOrderid();
        if (orderid == null || StringUtils.isEmpty(orderid)) {
            result.setMessage("仅支持到货单下推发签入库");
            return result;
        }
        List<String> whIds = epcprelist.stream().map(it -> it.getWarehouseId()).distinct().collect(Collectors.toList());
        if (whIds.size() != 1) {
            result.setMessage("仅支持单仓库作业");
            return result;
        }
        List<String> procodes = epcprelist.stream().map(it -> it.getProductcode()).distinct().collect(Collectors.toList());
        if (procodes.size() != 1) {
            result.setMessage("仅支持单物料作业");
            return result;
        }
        String orderdetailid = tempEntity.getOrderdetailid();
        //检查标签是否在库
        List<String> epcs = epcprelist.stream().map(it -> it.getEpccode()).collect(Collectors.toList());
        List<EpcEntity> list_epcEntity = epclistService.SelectByEpcs(epcs, tenantId);
        boolean flagEpcUsed = EpcotherService.CheckEpcUsed(list_epcEntity);
        if (flagEpcUsed) {
            result.setMessage("标签已占用");
            return result;
        }
        String warehouseId = tempEntity.getWarehouseId();
        if (StringUtils.isEmpty(warehouseId)) return result;
        if (StringUtils.isEmpty(modifier)) modifier = tempEntity.getModifier();
        //物料数据同步
        String productCode = tempEntity.getProductcode();
        ProductEntity productEntity = productService.SelectByCode(productCode, tenantId);
        if (productEntity != null) {
            productService.AutoDataEditById(String.valueOf(productEntity.getId()), productEntity.getProductApplyRangeId(), tenantId);
            productEntity = productService.SelectByCode(productCode, tenantId);
        }
//        else productService.EventProductEditStep(tenantId, productCode);

        //并本地入库 单据类型,1入库单(分配标签),2发货单,3到货单(到货分配标签、上架)
        WarehouseEntity warehouseEntity = warehouseService.SelectById(Long.parseLong(warehouseId), tenantId);
        int sourcetype = 1; //用于区分PC/pad
        ordertype = StringUtils.isEmpty(ordertype) ? "3" : ordertype;
        for (PrelableEntity item : epcprelist) {
            item.setOrdertype(ordertype);
            //补默认SKU
            if (StringUtils.isEmpty(item.getProductskuId())) {
                if (productEntity != null) {
                    item.setProductskuId(productEntity.getDefaultSKUId());
                    item.setProductskuname(productEntity.getProductName());
                }
            }
            //补仓库编码
            if (StringUtils.isEmpty(item.getWarehousecode())) {
                if (warehouseEntity != null) {
                    item.setWarehousecode(warehouseEntity.getCode());
                    item.setWarehousename(warehouseEntity.getWarehouseName());
                }
            }
        }

        // 提交本地-提交用友-回写本地
        String batchNum = MyTool.GenerateBatchnoDXQ(ordertype);//私有批次 发签批次号
        result = epclistService.SubmitEpclist(epcprelist, tenantId, userId, sourcetype, batchNum);
        if (result.getStatus() != 1) return result;
        // 批次入库更新
        String batchno_dxq = MyTool.GenerateBatchnoDXQ(ordertype);//私有批次 入库批次号
        Integer iInt = storerecordService.EditBatchno_dxq(epcs, orderid, ordertype, tenantId, batchno_dxq);
        //提交用友(组装数据提交用友)
        result = SubmitEpclistForYonyou(epcprelist, orderid, orderdetailid, tenantId, batchno_dxq);
        if (result.getStatus() != 1) {
            // 失败回退
            List<String> epcsDel = epcprelist.stream().map(it -> it.getEpccode()).distinct().collect(Collectors.toList());
            epclistService.DeleteInsertEntityListByOrderId(epcsDel, orderid, tenantId);
            return result;
        }
        //写用友入库完成单据信息
        String modelString = JSONObject.toJSONString(result.getData());

        //回写本地数据
        YonyouInReturnBean model = JSONObject.parseObject(modelString, YonyouInReturnBean.class);
        String batch_no = batchno_dxq; //入库批次号用于回写
        result = epclistService.SubmitEpclistCallback(epcprelist, model, tenantId, modifier, batch_no, ordertype);
        if (result.getStatus() != 1) {
            try {
                OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                recordEntity.setTenant_id(tenantId);
                recordEntity.setOrderid(orderid);
                recordEntity.setOrderdetailids(orderdetailid);
                recordEntity.setActioncode("pc_callback");
                recordEntity.setPickbatchno(batch_no);
                recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                recordEntity.setRemarkyonyou(modelString);
                recordEntity.setRemarkdxq(JSONObject.toJSONString(epcprelist));
                recordEntity.setRemark(result.getMessage());
                recordEntity.setModifier(modifier);
                recordEntity.setStatus(result.getStatus());
                orderNoticeService.InsertEntity(recordEntity);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
            result.setMessage("本地回写失败");
            result.setStatus(1);
        }
        return result;
    }

    /**
     * 本地入库回写失败重置
     *
     * @param id      单据Id
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/restorebyid")
    public DataResult RestoreById(String id, HttpServletRequest request) throws Exception {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        String ordertype = (String) reqParams.get("ordertype");

        OrderNoticeEntity entity = orderNoticeService.selectById(Integer.parseInt(id));
        if (entity == null) return result;
        if (entity.getStatus() == 1) {
            result.setMessage("操作成功");
            return result;
        }
        String orderid = entity.getOrderid();
        String modelString = entity.getRemarkyonyou();
        String epcprelistString = entity.getRemarkdxq();
        String batchno_dxq = entity.getPickbatchno(); //配货批次号
        if (StringUtils.isEmpty(modifier)) modifier = entity.getModifier();
        if (StringUtils.isEmpty(modelString) || StringUtils.isEmpty(epcprelistString)
                || StringUtils.isEmpty(batchno_dxq) || StringUtils.isEmpty(modifier)) {
            return result;
        }
        YonyouInReturnBean model = JSONObject.parseObject(modelString, YonyouInReturnBean.class);
        List<PrelableEntity> epcprelist = JSONObject.parseArray(epcprelistString, PrelableEntity.class);
        result = epclistService.SubmitEpclistCallback(epcprelist, model, tenantId, modifier, batchno_dxq, ordertype);
        if (result.getStatus() == 1) {
            //本地单据状态修改 提示数据同步到用友
            orderNoticeService.EditEntityStatusForPick(orderid, DxqConfig.TypeFail, 1, DxqConfig.StatusOk, modifier,
                    batchno_dxq, tenantId);
        }
        return result;
    }

    /**
     * 用友入库接口
     * 获取到货详情数据，组装入库提交数据
     * PC 模拟手持收货入库，然后执行上架
     * @return
     */
    private DataResult SubmitEpclistForYonyou(List<PrelableEntity> datalist, String orderid, String orderdetailid,
                                              String tenantId, String batchno_dxq) throws IOException {
        DataResult result = new DataResult(0, "操作失败");
        String warehouseId = datalist.get(0).getWarehouseId();
        DataResult tempResDH = epclistService.GetOrderDH(orderid, orderdetailid, tenantId);
        if (tempResDH.getStatus() != 1) return tempResDH;
        OrderDetailDHBean tempBean = (OrderDetailDHBean) tempResDH.getData();

        tempResDH = epclistService.MakeDataForDHSumit(datalist, tempBean, orderdetailid, tenantId, batchno_dxq);
        if (tempResDH.getStatus() != 1) return tempResDH;

        YonyouInParamBean entity = (YonyouInParamBean) tempResDH.getData();
        //单据仓库和指定仓库冲突
        if (!entity.getWarehouse().equals(warehouseId)) {
            entity.setWarehouse(warehouseId);
        }
        result = epclistService.OrderDHSubmit(entity, tenantId);

        return result;
    }

    /**
     * 迁移脚本功能 库存查询接口
     * /gdgy/api/isv2/epclist/EpcPageForReact?pagenum=1&pagesize=10&tenant_id=
     */
    @PostMapping("/EpcPageForReact")
    public DataResult EpcPageForReact(HttpServletRequest request, @RequestBody ReactEpcpageParam entity) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        try {
            Map params = RequestTool.getParamsPage(request, result);
            int pagenum = result.getPageNum();
            int pagesize = result.getPageSize();
            int m = result.initStartNumber();

            List<ReactEpcpageEntity> dataList = epclistService.SelectPageForReact(tenantId, m, pagesize, entity);
            int total = epclistService.SelectPageForReactCount(tenantId, entity);

            result = new DataResult(1, "操作成功");
            result.setPageParams(dataList, total);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
}
